'use strict';

const Service = require('egg').Service;

class AnalysisService extends Service {
  // 衣服使用频率分析
  async getClothingUsageFrequency(userId, timeRange = '30d') {
    const { Op } = this.app.Sequelize;
    
    // 计算时间范围
    const days = parseInt(timeRange.replace('d', ''));
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // 获取穿搭记录
    const wearRecords = await this.ctx.model.WearRecord.findAll({
      where: {
        user_id: userId,
        wear_date: {
          [Op.gte]: startDate
        }
      },
      include: [{
        model: this.ctx.model.Outfit,
        as: 'outfit',
        include: [{
          model: this.ctx.model.Clothing,
          as: 'clothes',
          through: {
            attributes: [],
            paranoid: false  // 中间表不使用软删除
          }
        }]
      }]
    });

    // 统计每件衣服的使用频率
    const usageStats = {};
    wearRecords.forEach(record => {
      if (record.outfit && record.outfit.clothes) {
        record.outfit.clothes.forEach(clothing => {
          if (!usageStats[clothing.id]) {
            usageStats[clothing.id] = {
              clothing,
              count: 0,
              lastWorn: null
            };
          }
          usageStats[clothing.id].count++;
          if (!usageStats[clothing.id].lastWorn || record.wear_date > usageStats[clothing.id].lastWorn) {
            usageStats[clothing.id].lastWorn = record.wear_date;
          }
        });
      }
    });

    // 转换为数组并排序
    const sortedStats = Object.values(usageStats)
      .sort((a, b) => b.count - a.count)
      .map(stat => ({
        clothing: {
          id: stat.clothing.id,
          name: stat.clothing.name,
          main_image: stat.clothing.main_image,
          category: stat.clothing.category?.name
        },
        wearCount: stat.count,
        lastWorn: stat.lastWorn,
        frequency: (stat.count / days * 30).toFixed(2) // 月频率
      }));

    // 获取未穿过的衣服
    const allClothing = await this.ctx.model.Clothing.findAll({
      where: { user_id: userId, status: 'available' },
      include: [{ model: this.ctx.model.Category, as: 'category' }]
    });

    const unwornClothing = allClothing.filter(clothing => 
      !usageStats[clothing.id]
    ).map(clothing => ({
      clothing: {
        id: clothing.id,
        name: clothing.name,
        main_image: clothing.main_image,
        category: clothing.category?.name
      },
      wearCount: 0,
      lastWorn: null,
      frequency: 0
    }));

    return {
      timeRange,
      totalRecords: wearRecords.length,
      mostWorn: sortedStats.slice(0, 10),
      leastWorn: sortedStats.slice(-10).reverse(),
      unworn: unwornClothing,
      summary: {
        totalClothing: allClothing.length,
        wornClothing: Object.keys(usageStats).length,
        unwornClothing: unwornClothing.length,
        averageWearFrequency: sortedStats.length > 0 ? 
          (sortedStats.reduce((sum, stat) => sum + stat.wearCount, 0) / sortedStats.length).toFixed(2) : 0
      }
    };
  }

  // 颜色使用偏好分析
  async getColorPreferenceAnalysis(userId) {
    // 获取用户所有衣服的颜色统计
    const clothing = await this.ctx.model.Clothing.findAll({
      where: { user_id: userId },
      attributes: ['id', 'color', 'color_hex']
    });

    // 获取穿着记录，通过 outfit 关联到 clothing
    const wearRecords = await this.ctx.model.WearRecord.findAll({
      where: { user_id: userId },
      include: [{
        model: this.ctx.model.Outfit,
        as: 'outfit',
        include: [{
          model: this.ctx.model.Clothing,
          as: 'clothes',
          through: {
            attributes: [],
            paranoid: false
          },
          attributes: ['id', 'color', 'color_hex']
        }]
      }]
    });

    // 统计颜色分布
    const colorStats = {};

    // 统计拥有的衣服颜色
    clothing.forEach(item => {
      const color = item.color || 'unknown';

      if (!colorStats[color]) {
        colorStats[color] = {
          color,
          colorHex: item.color_hex,
          count: 0,
          wearCount: 0
        };
      }
      colorStats[color].count++;
    });

    // 统计穿着频率
    wearRecords.forEach(record => {
      if (record.outfit && record.outfit.clothes) {
        record.outfit.clothes.forEach(clothing => {
          const color = clothing.color || 'unknown';
          if (colorStats[color]) {
            colorStats[color].wearCount++;
          }
        });
      }
    });

    // 转换为数组并计算偏好度
    const colorAnalysis = Object.values(colorStats)
      .map(stat => ({
        ...stat,
        percentage: ((stat.count / clothing.length) * 100).toFixed(1),
        wearFrequency: stat.wearCount,
        preferenceScore: (stat.wearCount / Math.max(stat.count, 1)).toFixed(2)
      }))
      .sort((a, b) => b.preferenceScore - a.preferenceScore);

    // 颜色搭配分析
    const colorCombinations = await this.analyzeColorCombinations(userId);

    return {
      totalColors: colorAnalysis.length,
      colorDistribution: colorAnalysis,
      topPreferredColors: colorAnalysis.slice(0, 5),
      leastPreferredColors: colorAnalysis.slice(-5).reverse(),
      colorCombinations,
      recommendations: this.generateColorRecommendations(colorAnalysis)
    };
  }

  // 搭配风格分析
  async getOutfitStyleAnalysis(userId) {
    const outfits = await this.ctx.model.Outfit.findAll({
      where: { user_id: userId },
      include: [{
        model: this.ctx.model.WearRecord,
        as: 'wearRecords'
      }]
    });

    // 统计风格分布
    const styleStats = {};
    outfits.forEach(outfit => {
      const style = outfit.style || 'casual';
      if (!styleStats[style]) {
        styleStats[style] = {
          style,
          count: 0,
          wearCount: 0,
          averageRating: 0,
          totalRating: 0
        };
      }
      styleStats[style].count++;
      styleStats[style].wearCount += outfit.wearRecords?.length || 0;
      if (outfit.rating) {
        styleStats[style].totalRating += outfit.rating;
      }
    });

    // 计算平均评分
    Object.values(styleStats).forEach(stat => {
      stat.averageRating = stat.count > 0 ? (stat.totalRating / stat.count).toFixed(1) : 0;
      stat.percentage = ((stat.count / outfits.length) * 100).toFixed(1);
    });

    const sortedStyles = Object.values(styleStats)
      .sort((a, b) => b.wearCount - a.wearCount);

    return {
      totalOutfits: outfits.length,
      styleDistribution: sortedStyles,
      mostPopularStyle: sortedStyles[0],
      styleEvolution: await this.analyzeStyleEvolution(userId),
      recommendations: this.generateStyleRecommendations(sortedStyles)
    };
  }

  // 购买建议分析
  async getBuyingSuggestionAnalysis(userId) {
    // 获取用户衣柜分析
    const clothing = await this.ctx.model.Clothing.findAll({
      where: { user_id: userId },
      include: [{ model: this.ctx.model.Category, as: 'category' }]
    });

    // 按分类统计
    const categoryStats = {};
    clothing.forEach(item => {
      const categoryName = item.category?.name || 'other';
      if (!categoryStats[categoryName]) {
        categoryStats[categoryName] = {
          category: categoryName,
          count: 0,
          colors: new Set(),
          styles: new Set(),
          avgPrice: 0,
          totalPrice: 0
        };
      }
      categoryStats[categoryName].count++;
      if (item.color) categoryStats[categoryName].colors.add(item.color);
      if (item.style) categoryStats[categoryName].styles.add(item.style);
      if (item.price) {
        categoryStats[categoryName].totalPrice += parseFloat(item.price);
      }
    });

    // 计算平均价格和多样性
    Object.values(categoryStats).forEach(stat => {
      stat.avgPrice = stat.count > 0 ? (stat.totalPrice / stat.count).toFixed(2) : 0;
      stat.colorDiversity = stat.colors.size;
      stat.styleDiversity = stat.styles.size;
      stat.colors = Array.from(stat.colors);
      stat.styles = Array.from(stat.styles);
    });

    // 生成购买建议
    const suggestions = this.generateBuyingSuggestions(categoryStats);

    return {
      categoryAnalysis: Object.values(categoryStats),
      suggestions,
      budgetRecommendations: this.generateBudgetRecommendations(categoryStats),
      missingItems: this.identifyMissingItems(categoryStats)
    };
  }

  // 季节性穿搭分析
  async getSeasonalWearAnalysis(userId, year = new Date().getFullYear()) {
    const { Op } = this.app.Sequelize;
    
    const startDate = new Date(year, 0, 1);
    const endDate = new Date(year, 11, 31);

    const wearRecords = await this.ctx.model.WearRecord.findAll({
      where: {
        user_id: userId,
        wear_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      include: [{
        model: this.ctx.model.Outfit,
        as: 'outfit',
        include: [{
          model: this.ctx.model.Clothing,
          as: 'clothes',
          through: {
            paranoid: false  // 中间表不使用软删除
          }
        }]
      }]
    });

    // 按季节分组
    const seasonalData = {
      spring: { months: [3, 4, 5], records: [], colors: {}, styles: {} },
      summer: { months: [6, 7, 8], records: [], colors: {}, styles: {} },
      autumn: { months: [9, 10, 11], records: [], colors: {}, styles: {} },
      winter: { months: [12, 1, 2], records: [], colors: {}, styles: {} }
    };

    wearRecords.forEach(record => {
      const month = new Date(record.wear_date).getMonth() + 1;
      let season = 'spring';
      
      if (seasonalData.summer.months.includes(month)) season = 'summer';
      else if (seasonalData.autumn.months.includes(month)) season = 'autumn';
      else if (seasonalData.winter.months.includes(month)) season = 'winter';

      seasonalData[season].records.push(record);

      // 统计颜色和风格
      if (record.outfit) {
        if (record.outfit.style) {
          seasonalData[season].styles[record.outfit.style] = 
            (seasonalData[season].styles[record.outfit.style] || 0) + 1;
        }
        
        if (record.outfit.clothes) {
          record.outfit.clothes.forEach(clothing => {
            if (clothing.color) {
              seasonalData[season].colors[clothing.color] = 
                (seasonalData[season].colors[clothing.color] || 0) + 1;
            }
          });
        }
      }
    });

    // 处理数据
    Object.keys(seasonalData).forEach(season => {
      const data = seasonalData[season];
      data.totalWears = data.records.length;
      data.topColors = Object.entries(data.colors)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 5)
        .map(([color, count]) => ({ color, count }));
      data.topStyles = Object.entries(data.styles)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 3)
        .map(([style, count]) => ({ style, count }));
      delete data.records; // 移除原始记录以减少数据量
    });

    return {
      year,
      seasonalAnalysis: seasonalData,
      insights: this.generateSeasonalInsights(seasonalData)
    };
  }

  // 辅助方法
  async analyzeColorCombinations(userId) {
    // 分析用户常用的颜色搭配
    return [
      { colors: ['black', 'white'], frequency: 15, rating: 4.5 },
      { colors: ['blue', 'white'], frequency: 12, rating: 4.2 },
      { colors: ['gray', 'black'], frequency: 8, rating: 4.0 }
    ];
  }

  generateColorRecommendations(colorAnalysis) {
    const recommendations = [];
    
    // 如果缺少基础色
    const basicColors = ['black', 'white', 'gray', 'navy'];
    const userColors = colorAnalysis.map(c => c.color.toLowerCase());
    
    basicColors.forEach(color => {
      if (!userColors.includes(color)) {
        recommendations.push({
          type: 'missing_basic',
          color,
          reason: `建议添加${color}色单品，这是百搭的基础色`
        });
      }
    });

    return recommendations;
  }

  async analyzeStyleEvolution(userId) {
    // 分析用户风格变化趋势
    return {
      trend: 'more_casual',
      description: '您的穿搭风格趋向更加休闲'
    };
  }

  generateStyleRecommendations(styleStats) {
    return [
      {
        type: 'diversify',
        suggestion: '尝试更多不同的风格搭配',
        reason: '增加穿搭的多样性'
      }
    ];
  }

  generateBuyingSuggestions(categoryStats) {
    const suggestions = [];
    
    // 检查各分类的数量
    const minCounts = {
      '上装': 10,
      '下装': 6,
      '外套': 4,
      '鞋子': 5,
      '配饰': 3
    };

    Object.entries(minCounts).forEach(([category, minCount]) => {
      const stat = categoryStats[category];
      if (!stat || stat.count < minCount) {
        suggestions.push({
          category,
          priority: 'high',
          reason: `${category}数量不足，建议增加${minCount - (stat?.count || 0)}件`,
          suggestedCount: minCount - (stat?.count || 0)
        });
      }
    });

    return suggestions;
  }

  generateBudgetRecommendations(categoryStats) {
    return {
      totalInvestment: Object.values(categoryStats)
        .reduce((sum, stat) => sum + parseFloat(stat.totalPrice || 0), 0),
      recommendations: [
        { category: '上装', suggestedBudget: 1000, reason: '基础单品投资' }
      ]
    };
  }

  identifyMissingItems(categoryStats) {
    const essentialItems = [
      { category: '上装', items: ['白衬衫', '基础T恤', '针织衫'] },
      { category: '下装', items: ['牛仔裤', '黑色长裤', '半身裙'] },
      { category: '外套', items: ['风衣', '西装外套'] },
      { category: '鞋子', items: ['小白鞋', '黑色皮鞋'] }
    ];

    return essentialItems.map(essential => ({
      category: essential.category,
      missingItems: essential.items,
      currentCount: categoryStats[essential.category]?.count || 0
    }));
  }

  generateSeasonalInsights(seasonalData) {
    return [
      {
        insight: '夏季偏爱浅色系搭配',
        data: seasonalData.summer.topColors
      },
      {
        insight: '冬季更多选择深色系',
        data: seasonalData.winter.topColors
      }
    ];
  }

  // 获取衣服分析数据
  async getClothingAnalysis(userId) {
    try {
      const clothing = await this.ctx.model.Clothing.findAll({
        where: { user_id: userId },
        include: [{
          model: this.ctx.model.Category,
          as: 'category'
        }]
      });

      const totalCount = clothing.length;

      // 分类分布
      const categoryDistribution = {};
      clothing.forEach(item => {
        const category = item.category?.name || '其他';
        categoryDistribution[category] = (categoryDistribution[category] || 0) + 1;
      });

      // 颜色分布
      const colorDistribution = {};
      clothing.forEach(item => {
        if (item.color) {
          colorDistribution[item.color] = (colorDistribution[item.color] || 0) + 1;
        }
      });

      return {
        totalCount,
        categoryDistribution: Object.entries(categoryDistribution).map(([name, count]) => ({ name, count })),
        colorDistribution: Object.entries(colorDistribution).map(([name, count]) => ({ name, count })),
        utilizationRate: 0.75 // 默认利用率
      };
    } catch (error) {
      console.error('获取衣服分析失败:', error);
      return { totalCount: 0, categoryDistribution: [], colorDistribution: [], utilizationRate: 0 };
    }
  }

  // 获取搭配分析数据
  async getOutfitAnalysis(userId) {
    try {
      const outfits = await this.ctx.model.Outfit.findAll({
        where: { user_id: userId }
      });

      const totalCount = outfits.length;

      // 风格分布
      const styleDistribution = {};
      outfits.forEach(outfit => {
        if (outfit.style) {
          styleDistribution[outfit.style] = (styleDistribution[outfit.style] || 0) + 1;
        }
      });

      // 季节分布
      const seasonDistribution = {};
      outfits.forEach(outfit => {
        if (outfit.season) {
          seasonDistribution[outfit.season] = (seasonDistribution[outfit.season] || 0) + 1;
        }
      });

      // 评分分布
      const ratingDistribution = {};
      outfits.forEach(outfit => {
        if (outfit.rating) {
          const rating = Math.floor(outfit.rating);
          ratingDistribution[rating] = (ratingDistribution[rating] || 0) + 1;
        }
      });

      const averageRating = outfits.length > 0
        ? outfits.reduce((sum, outfit) => sum + (outfit.rating || 0), 0) / outfits.length
        : 0;

      return {
        totalCount,
        styleDistribution: Object.entries(styleDistribution).map(([name, count]) => ({ name, count })),
        seasonDistribution: Object.entries(seasonDistribution).map(([name, count]) => ({ name, count })),
        ratingDistribution: Object.entries(ratingDistribution).map(([rating, count]) => ({ rating: parseInt(rating), count })),
        averageRating: Math.round(averageRating * 100) / 100
      };
    } catch (error) {
      console.error('获取搭配分析失败:', error);
      return { totalCount: 0, styleDistribution: [], seasonDistribution: [], ratingDistribution: [], averageRating: 0 };
    }
  }

  // 获取穿搭分析数据
  async getWearAnalysis(userId) {
    try {
      const wearRecords = await this.ctx.model.WearRecord.findAll({
        where: { user_id: userId },
        include: [{
          model: this.ctx.model.Outfit,
          as: 'outfit'
        }]
      });

      const totalWears = wearRecords.length;

      // 月度趋势
      const monthlyTrend = {};
      wearRecords.forEach(record => {
        const month = new Date(record.wear_date).getMonth() + 1;
        monthlyTrend[month] = (monthlyTrend[month] || 0) + 1;
      });

      // 周模式
      const weeklyPattern = {};
      wearRecords.forEach(record => {
        const day = new Date(record.wear_date).getDay();
        const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const dayName = dayNames[day];
        weeklyPattern[dayName] = (weeklyPattern[dayName] || 0) + 1;
      });

      // 热门搭配
      const outfitCounts = {};
      wearRecords.forEach(record => {
        if (record.outfit_id) {
          outfitCounts[record.outfit_id] = (outfitCounts[record.outfit_id] || 0) + 1;
        }
      });

      const popularOutfits = Object.entries(outfitCounts)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 5)
        .map(([outfitId, count]) => ({ outfitId: parseInt(outfitId), count }));

      return {
        totalWears,
        monthlyTrend: Object.entries(monthlyTrend).map(([month, count]) => ({ month: parseInt(month), count })),
        weeklyPattern: Object.entries(weeklyPattern).map(([day, count]) => ({ day, count })),
        popularOutfits
      };
    } catch (error) {
      console.error('获取穿搭分析失败:', error);
      return { totalWears: 0, monthlyTrend: [], weeklyPattern: [], popularOutfits: [] };
    }
  }

  // 获取综合分析报告
  async getComprehensiveReport(userId) {
    try {
      // 获取各种分析数据
      const [
        clothingAnalysis,
        outfitAnalysis,
        wearAnalysis,
        seasonalAnalysis
      ] = await Promise.all([
        this.getClothingAnalysis(userId),
        this.getOutfitAnalysis(userId),
        this.getWearAnalysis(userId),
        this.getSeasonalWearAnalysis(userId)
      ]);

      // 生成综合报告
      const report = {
        summary: {
          totalClothing: clothingAnalysis.totalCount || 0,
          totalOutfits: outfitAnalysis.totalCount || 0,
          totalWears: wearAnalysis.totalWears || 0,
          averageRating: outfitAnalysis.averageRating || 0
        },
        clothing: {
          categoryDistribution: clothingAnalysis.categoryDistribution || [],
          colorDistribution: clothingAnalysis.colorDistribution || [],
          utilizationRate: clothingAnalysis.utilizationRate || 0
        },
        outfits: {
          styleDistribution: outfitAnalysis.styleDistribution || [],
          seasonDistribution: outfitAnalysis.seasonDistribution || [],
          ratingDistribution: outfitAnalysis.ratingDistribution || []
        },
        wearPatterns: {
          monthlyTrend: wearAnalysis.monthlyTrend || [],
          weeklyPattern: wearAnalysis.weeklyPattern || [],
          popularOutfits: wearAnalysis.popularOutfits || []
        },
        seasonal: {
          seasonalPreferences: seasonalAnalysis.seasonalData || {},
          insights: seasonalAnalysis.insights || []
        },
        recommendations: [
          '建议增加基础款单品的搭配',
          '尝试更多颜色组合',
          '关注季节性搭配趋势'
        ],
        generatedAt: new Date()
      };

      return report;
    } catch (error) {
      console.error('生成综合报告失败:', error);
      // 返回默认报告
      return {
        summary: {
          totalClothing: 0,
          totalOutfits: 0,
          totalWears: 0,
          averageRating: 0
        },
        clothing: {
          categoryDistribution: [],
          colorDistribution: [],
          utilizationRate: 0
        },
        outfits: {
          styleDistribution: [],
          seasonDistribution: [],
          ratingDistribution: []
        },
        wearPatterns: {
          monthlyTrend: [],
          weeklyPattern: [],
          popularOutfits: []
        },
        seasonal: {
          seasonalPreferences: {},
          insights: []
        },
        recommendations: [
          '开始记录你的穿搭数据',
          '添加更多衣服和搭配',
          '定期更新穿着记录'
        ],
        generatedAt: new Date()
      };
    }
  }
}

module.exports = AnalysisService;
